package com.tingyuge.thinking.spring.ioc.overview.dependency.lookup;

import com.tingyuge.thinking.spring.ioc.overview.annotation.Supper;
import com.tingyuge.thinking.spring.ioc.overview.domain.SuperUser;
import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

/**
 * 依赖查找示例
 * 1.通过名称查找
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/15
 */
public class DependencyLookupDemo {

    public static void main(String[] args) {
        /*配置 xml 配置文件*/
        //获取 spring 应用上下文
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("META-INF/dependency-lookup-context.xml");
        lookupByType(beanFactory);

        //按照类型查找集合对象
        lookupCollectionByType(beanFactory);
        //通过注解查找
        lookupByAnnotation(beanFactory);

//        lookupInRealTime(beanFactory);
//        lookupInLazy(beanFactory);
    }

    private static void lookupByAnnotation(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory =(ListableBeanFactory)beanFactory;
            Map<String, User> userMap = (Map)listableBeanFactory.getBeansWithAnnotation(Supper.class);
            System.out.println("查找到 @super标注 的所有的User 集合对象:  "+userMap);
        }
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory =(ListableBeanFactory)beanFactory;
            Map<String, User> userMap = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有的User 集合对象:  "+userMap);
        }
    }

    private static void lookupByType(BeanFactory beanFactory) {
        User bean = beanFactory.getBean(User.class);
        System.out.println("类型查找： "+ bean);
    }

    private static void lookupInRealTime(BeanFactory beanFactory){
        User user = (User) beanFactory.getBean("user");
        System.out.println("实时查找: "+ user);
    }
    private static void lookupInLazy(BeanFactory beanFactory){
        /*factoryBean*/
        ObjectFactory<User> objectFactory = ( ObjectFactory<User>) beanFactory.getBean("objectFactory");
        User user = objectFactory.getObject();
        System.out.println("延时查找: "+ user);
    }
}
